<?php

/**
 *		//任务系统函数//
 *		//这是一份试验品，地宝网5毛管理系统，由大街编写（zhongmingzi@gmail.com）
 *		//本程序默认环境：Zend Optimizer Yes / 3.3.3
 *		//		Apache/2.0.63 (Win32) PHP/5.2.12
 *		//		MySQL 支持 Yes / client lib version 5.0.89
 *		//		GD library Yes / bundled (2.0.34 compatible)
 *		//		eAccelerator/Memcache/xcache Yes
 *		//		cURL support enabled
 *		//时间：2011-01-10//
 */

 function register() {
	global $_G;
	$email = $_G['gp_email'];
	$username = $_G['gp_username'];//真实姓名
	$password = $passworded = $_G['gp_password'];
	$password1 = $_G['gp_passworded'];
	$gender = $_G['gp_gender'];//0为未知，1为男，2为女
	$birthyear = $_G['gp_birthyear'];
	$birthmonth = $_G['gp_birthmonth'];
	$birthday = $_G['gp_birthday'];
	$address = $_G['gp_address'];
	$zipcode = $_G['gp_zipcode'];
	$mobile = $_G['gp_mobile'];
	$job = $_G['gp_job'];
	$idcard = $_G['gp_idcard'];
	$alipay = $_G['gp_alipay'];
	$password = md5($password);
	
	if($password1 != $passworded) return -6;//两次密码输入不同
	if(!isemail($email)) return -1;//非法Email地址
	if(!preg_match('/^([\xE4-\xE9][\x80-\xBF][\x80-\xBF])+$/', $username)) return -2;//姓名简单匹配
	if(!preg_match('/^13[0-9]{1}[0-9]{8}$|15[0189]{1}[0-9]{8}$|189[0-9]{8}$/', $mobile)) return -3;//手机匹配
	if(!preg_match('/^[1-9]\d{5}$/', $zipcode)) return -4;//邮编错误
	if(!preg_match('/^\d{15}(\d{2}[A-Za-z0-9])?$/', $idcard)) return -5;//身份证验证
 
	$data = array(
		'email' => $email,
		'username' => $username,
		'password' => $password,
		'status' => 0,//0表示待审核， 1表示通过， 2表示封禁
		'gender' => $gender,
		'birthyear' => $birthyear,
		'birthmonth' => $birthmonth,
		'birthday' => $birthday,
		'address' => $address,
		'zipcode' => $zipcode,
		'mobile' => $mobile,
		'job' => $job,
		'idcard' => $idcard,
		'alipay' => $alipay,
		'adminid' => 0,
		'groupid' => 1,
		'groupexpiry' => 0,
		'regdate' => TIMESTAMP,
		'regip' => $_G['ip'],
		'lastip' => $_G['ip'],
		'lastvisit' => TIMESTAMP,
		'lastactivity' => TIMESTAMP,
	);
	$id = DB::insert('user', $data, true);
	if($id) DB::insert('user_count', array('uid' => $id));
	writelog('memberlog', "register\t$username\t$password\t{$_G['ip']}\t".TIMESTAMP);//注册记录
	if($id > 0 && login($username, $passworded, true)) return $id;
	else return false;
 }
 
 function login($username, $password, $force = false) {
	global $_G;
	$password = md5($password);
	$n = DB::result_first("SELECT uid FROM ".DB::table('user')." WHERE username = '$username' AND password = '$password'");
	$failed = empty($n) ? '' : 'Failed';
	writelog('memberlog', "login$failed\t$username\t$password\t{$_G['ip']}\t".TIMESTAMP);//登录记录
	if($n || $force) {
		$auth = authcode($n."\t".$password, 'ENCODE');
		$expiry = $_G['gp_remember'] == 1 ? 604800 : 0;//保持登陆一周
		dsetcookie('auth', $auth, $expiry);
		return true;
	} else return false;
 }
 
 function showbirthday($type = 'y') {
	global $_G;
	if($type == 'y'){
		$string .= '<select id="birthyear" name="birthyear"><option value="">年</option>\n\r';
		for($i = date('Y'); $i >= 1949; $i--){
			$str = $_G['member']['birthyear'] == $i ? 'selected=\"selected\"' : '';
			$string .= "<option value=\"$i\" $str >$i</option>\n\r\\t\t\t";
		}
		$string .= "</select>";
	}elseif($type == 'm'){
		$string .= '<select id="birthmonth" name="birthmonth"><option value="">月</option>\n\r';
		for($i = 1; $i <= 12; $i++){
			$str = $_G['member']['birthmonth'] == $i ? 'selected=\"selected\"' : '';
			$string .= "<option value=\"$i\" $str >$i</option>/n/r/t/t/t/t";
		}
		$string .= "</select>";
	}elseif($type == 'd'){
		$string .= '<select id="birthday" name="birthday"><option value="">日</option>\n\r';
		for($i = 1; $i <= 31; $i++){
			$str = $_G['member']['birthday'] == $i ? 'selected=\"selected\"' : '';
			$string .= "<option value=\"$i\" $str >$i</option>/n/r/t/t/t/t";
		}
		$string .= "</select>";
	}
	return $string;
}

function showgender() {
	global $_G;
	$str0 = $_G['member']['gender'] == 0 ? 'selected=\"selected\"' : '';
	$str1 = $_G['member']['gender'] == 1 ? 'selected=\"selected\"' : '';
	$str2 = $_G['member']['gender'] == 2 ? 'selected=\"selected\"' : '';
	$string .= "<select name=\"gender\" id=\"gender\">\n\r<option value=\"0\" $str0 >无</option>\n\r<option value=\"1\" $str1 >男</option>\n\r<option value=\"2\" $str2 >女</option>\n\r</select>";
	return $string;
}

function logout($formhash) {
	global $_G;
	if($formhash != FORMHASH) return false;
	dsetcookie('auth', '');
	return true;
}

function verifyuser($page, $limit = 20) {
	global $_G;
	if($_G['adminid'] < 1) return false;
	$sql = "SELECT * FROM ".DB::table('user')." WHERE status = 0 ORDER BY regdate DESC ";
	$f = prepage($page, $limit, $sql);
	$return['ptotal'] = $f['ptotal'];
	$sql .= "LIMIT {$f['offset']}, {$f['limit']}";
	$q = DB::query($sql);
	while($r = DB::fetch($q)) {
		$r['gender'] = $r['gender'] == 0 ? "未知" : ($r['gender'] == 1 ? "男" : "女");
		$r['age'] = date('Y') - $r['birthyear'];
		$return['data'][] = $r;
	}
	return $return;
}

//true的情况下，通过，否则删除用户信息
function verifyuid($uids, $type = true) {
	global $_G;
	if($_G['adminid'] < 1) return false;
	if(!is_array($uids)) $uids = array($uids);
	$data = array('status' => 1);
	$co = implode_in($uids);
	$sql = " uid IN ($co)";
	if($type) DB::update('user', $data, $sql);
	else {
		DB::delete('user', $sql);
		DB::delete('user_count', $sql);
	}
	return true;
}

function newtask($title, $text, $tasklimits, $starttime, $endtime, $price, $displayorder, $available = true, $type = 1, $exid = 0) {
	global $_G;
	if($_G['adminid'] < 1) return false;
	$tasklimits = (int) $tasklimits;
	$starttime = (int) $starttime;
	$endtime = (int) $endtime;
	$price = (int) $price;
	$displayorder = (int) $displayorder;
	$exid = (int) $exid;
	$data = array(
		'type' => $type,
		'name' => $title,
		'description' => $text,
		'tasklimits' => $tasklimits,
		'already' => 0,
		'starttime' => $starttime,
		'endtime' => $endtime,
		'prize' => $price,
		'available'=> $available,
		'displayorder' => $displayorder,
		'exid' => $exid,
		'dateline' => TIMESTAMP
	);
	$id = DB::insert('task', $data, true);
	if(!$id) return false;
	else return $id;
}

function taskdetail($id) {
	$id = (int) $id;
	$sql = "SELECT * FROM ".DB::table('task')." WHERE taskid = $id";
	return DB::fetch_first($sql);
}

function edittask($taskid, $title, $text, $tasklimits, $starttime, $endtime, $price, $displayorder, $available = true, $type = 1, $exid = 0) {
	global $_G;
	$taskid = (int) $taskid;
	$exid = (int) $exid;
	if($_G['adminid'] < 1) return false;
	$data = array(
		'type' => $type,
		'name' => $title,
		'description' => $text,
		'tasklimits' => $tasklimits,
		'already' => 0,
		'starttime' => $starttime,
		'endtime' => $endtime,
		'prize' => $price,
		'available'=> $available,
		'exid' => $exid,
		'displayorder' => $displayorder,
	);
	return DB::update('task', $data, "taskid = $taskid");
}

function viewtask($taskid) {
	$taskid = (int) $taskid;
	$r = DB::fetch_first("SELECT * FROM ".DB::table('task')." WHERE taskid = $taskid");
	$r['sy'] = $r['tasklimits'] - $r['already'];
	$r['exided'] = $r['exid'];
	$r['exid'] = "http://www.tiboo.cn/read.php?tid=".$r['exid'];
	return $r;
}

//这里类型包括1，主题；2，帖子；3，综合
function tasklist($type, $page, $limit = 20) {
	global $_G;
	$type = (int) $type;
	$sqladd = $type == 3 ? "" : " AND type = $type";
	$sql = "SELECT * FROM ".DB::table('task')." WHERE 1 $sqladd ORDER BY dateline,displayorder DESC ";
	$f = prepage($page, $limit, $sql);
	$return['ptotal'] = $f['ptotal'];
	$return['total'] = $f['total'];
	$sql .= "LIMIT {$f['offset']}, {$f['limit']}";
	$q = DB::query($sql);
	while($r = DB::fetch($q)) {
		$return['id'][] = $r['taskid'];
		$r['sy'] = $r['tasklimits'] - $r['already'];
		$r['exid'] = "http://www.tiboo.cn/read.php?tid=".$r['exid'];
		$return['data'][] = $r;
	}
	return $return;
}

//查看是否报名,输入所有任务id，返回已经报名的id
function isapplied($array) {
	global $_G;
	$in = implode_in($array);
	$sql = "SELECT taskid FROM ".DB::table('task_user')." WHERE taskid IN ($in) AND uid = {$_G['uid']}";
	$q = DB::query($sql);
	while($v = DB::fetch($q)) {
		$return[] = $v['taskid'];
	}
	return $return;
}

//报名
function applytask($taskid, $type) {
	global $_G;
	$taskid = (int) $taskid;
	if($_G['uid'] < 1) return 0;
	$lm = DB::result_first("SELECT `tasklimits` -  `already` FROM ".DB::table('task')." WHERE  `taskid` =$taskid");
	if($lm < 1 ) return -1;
	$data = array(
		'taskid' => $taskid,
		'uid' => $_G['uid'],
		'username' => $_G['username'],
		'status' => 0,
		'dateline' => TIMESTAMP,
	);
	$typesql = $type == 1 ? "threads = threads + 1" : "posts = posts + 1";
	if(DB::insert('task_user', $data)) {
		DB::query("UPDATE ".DB::table('task')." SET already = already + 1 WHERE taskid = $taskid");
		DB::query("UPDATE ".DB::table('user_count')." SET tasks = tasks + 1, $typesql WHERE uid = {$_G['uid']}");
		return 1;
	} else return 0;
}

//统计还是有问题的！最好是不要删除任务
function deltask($taskid, $type) {
	global $_G;
	if($_G['adminid'] < 1) return false;
	$taskid = (int) $taskid;
	DB::delete('task', "taskid = $taskid");
	DB::delete('task_user', "taskid = $taskid");
	DB::delete('task_log', "taskid = $taskid");
	$typesql = $type == 1 ? "threads = threads - 1" : "posts = posts - 1";
	DB::query("UPDATE ".DB::table('user_count')." SET $typesql WHERE uid = {$_G['uid']}");
	return true;
}

function getinfobyid($uid) {
	$uid = (int) $uid;
	global $_G;
	$sql = "SELECT * FROM ".DB::table('user')." LEFT JOIN ".DB::table('user_count')." USING(uid) WHERE uid = '$uid'";
	return DB::fetch_first($sql);
}

function mythreadtask($uid = 0, $page = 1, $limit = 20, $type = 1) {
	global $_G;
	$uid = (int) $uid;
	if($uid == 0) $sql = "SELECT * FROM  ".DB::table('task')."  WHERE type = $type ";
	else $sql = "SELECT * FROM ".DB::table('task_user')." LEFT JOIN ".DB::table('task')." USING(taskid) WHERE uid = $uid AND type = $type ";
	$f = prepage($page, $limit, $sql);
	$return['ptotal'] = $f['ptotal'];
	$return['total'] = $f['total'];
	$sql .= "LIMIT {$f['offset']}, {$f['limit']}";
	$q = DB::query($sql);
	while($v = DB::fetch($q)) {
		$v['description'] = dstrip_tags($v['description']);
		$v['names'] = cutstr($v['name'], 20);
		$v['descriptions'] = cutstr($v['description'], 40);
		$return['data'][] = $v;
	}
	return $return;
}

function postaddress($taskid, $type, $detail) {
	global $_G;
	if(!is_array($detail)) $detail = array($detail);
	foreach($detail as $v) {
		if(trim($v) == '') break;
		if($type == 1 && !preg_match("/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/", $v)) break;
		$data = array(
			'taskid' => $taskid,
			'uid' => $_G['uid'],
			'type' => $type,
			'detail' => $v,
			'dateline' => TIMESTAMP,
		);
		DB::insert('task_log', $data, false, false, true);
		if(DB::affected_rows() == 1) {
			DB::query("UPDATE ".DB::table('task')." SET posts = posts + 1 WHERE taskid = $taskid");
			DB::query("UPDATE ".DB::table('task_user')." SET posts = posts + 1 WHERE taskid = $taskid AND uid = {$_G['uid']}");
		}
	}
	return true;
}

function viewthreadtask($taskid, $type, $page = 1, $limit = 20) {
	global $_G;
	$taskid = (int) $taskid;
	$type = (int) $type;
	
	if($taskid == 0 && $type == 0) $sql = "SELECT t.name,u.username,l.* FROM ".DB::table('task_log')." l LEFT JOIN ".DB::table('task')." t USING(taskid) LEFT JOIN ".DB::table('user')." u USING(uid)  WHERE  l.status = 0 ORDER BY l.dateline DESC ";
	else $sql = "SELECT * FROM ".DB::table('task_log')." WHERE taskid = $taskid AND uid = {$_G['uid']} AND type = $type ";
	$f = prepage($page, $limit, $sql);
	$return['ptotal'] = $f['ptotal'];
	$return['total'] = $f['total'];
	$sql .= "LIMIT {$f['offset']}, {$f['limit']}";
	$q = DB::query($sql);
	while($v = DB::fetch($q)) {
		$v['status'] = $v['status'] == 0 ? '未审核' : ($v['status'] == 1 ? '审核通过' : '审核未通过') ;
		$return['data'][] = $v;
	}
	return $return;
}

function taskusername($taskid, $page, $limit) {
	$sql = "SELECT * FROM ".DB::table('task_user')." WHERE taskid = $taskid  ";
	$f = prepage($page, $limit, $sql);
	$return['ptotal'] = $f['ptotal'];
	$return['total'] = $f['total'];
	$sql .= "LIMIT {$f['offset']}, {$f['limit']}";
	$q = DB::query($sql);
	while($v = DB::fetch($q)) {
		$return['data'][] = $v;
	}
	return $return;
}

function viewext($uid, $page, $limit) {
	$uid = (int) $uid;
	$sql = "SELECT * FROM ".DB::table('money_log')." WHERE uid = $uid ORDER BY dateline DESC ";
	$f = prepage($page, $limit, $sql);
	$return['ptotal'] = $f['ptotal'];
	$return['total'] = $f['total'];
	$sql .= "LIMIT {$f['offset']}, {$f['limit']}";
	$q = DB::query($sql);
	while($v = DB::fetch($q)) {
		$return['data'][] = $v;
	}
	return $return;
}

function deltaskurl($id, $uid) {
	global $_G;
	if($_G['uid'] == 0 || $_G['uid'] != $uid) return false;
	if(!is_array($id)) $id = array($id);
	foreach($id as $v) {
		DB::query("UPDATE ".DB::table('task')." SET posts = posts - 1 WHERE taskid = (SELECT taskid FROM ".DB::table('task_log')." WHERE lid = $v)");
		DB::query("UPDATE ".DB::table('task_user')." SET posts = posts - 1 WHERE taskid = (SELECT taskid FROM ".DB::table('task_log')." WHERE lid = $v) AND uid = {$_G['uid']}");
		DB::delete('task_log', "lid = $v");
	}
	return true;
}

//在这里status为0的时候为未处理。1为审核通过，2为审核未通过//第一次审核通过
function verifytask($lids, $type = true) {
	global $_G;
	if($_G['adminid'] < 1) return false;
	if(!is_array($lids)) $lids = array($lids);
	$co = implode_in($lids);
	$sql = " lid IN ($co)";
	if($type) {
		DB::update('task_log', array('status' => 1), $sql);
		foreach($lids as $v) {
			DB::query("UPDATE ".DB::table('task_user')." SET passed = passed + 1 WHERE taskid = (SELECT taskid FROM ".DB::table('task_log')." WHERE lid = $v) AND uid = (SELECT uid FROM ".DB::table('task_log')." WHERE lid = $v)");
			DB::query("INSERT INTO ".DB::table('money_log')." SET taskid = (SELECT taskid FROM ".DB::table('task_log')." WHERE lid = $v), lid = $v, uid = (SELECT uid FROM ".DB::table('task_log')." WHERE lid = $v), type = 1, passed = 1, price = (SELECT prize FROM ".DB::table('task')." WHERE taskid = (SELECT taskid FROM ".DB::table('task_log')." WHERE lid = $v)), dateline = ".TIMESTAMP, 'SILENT');
			DB::query("UPDATE ".DB::table('task_count')." SET tomonthmoney = tomonthmoney + (SELECT prize FROM ".DB::table('task')." WHERE taskid = (SELECT taskid FROM ".DB::table('task_log')." WHERE lid = $v)), extcredits = extcredits + (SELECT prize FROM ".DB::table('task')." WHERE taskid = (SELECT taskid FROM ".DB::table('task_log')." WHERE lid = $v)), tasked = tasked + 1, threads = threads + 1 WHERE uid = (SELECT uid FROM ".DB::table('task_log')." WHERE lid = $v)");
		}
	} else {
		DB::update('task_log', array('status' => 2), $sql);
		foreach($lids as $v) {
			DB::query("UPDATE ".DB::table('task_user')." SET refused = refused + 1 WHERE taskid = (SELECT taskid FROM ".DB::table('task_log')." WHERE lid = $v) AND uid = (SELECT uid FROM ".DB::table('task_log')." WHERE lid = $v)");
		}
	}
	return true;
}

//审核回复,包括更改状态，更新统计，更新列表//这里效率未测，最好不要传入数组uid
//第一次检验完成
function verifypost($taskid, $uid, $type = true) {
	global $_G;
	if($_G['adminid'] < 1) return false;
	if(!is_array($uid)) $uid = array($uid);
	
	foreach($uid as $v) {
		//查询马甲
		$q = DB::query("SELECT windid FROM ".DB::table('user_sub')." WHERE uid = $v");
		while($r = DB::fetch($q)) {
			$winds[] = $r['windid'];
		}
		$data['windid'] = implode_in($winds);
		$return['data'][$v] =$pcount =  do_api('countpost', $data);
		
		if($type == true) {
			DB::query("INSERT INTO ".DB::table('money_log')." SET taskid = $taskid, lid = 0, uid = $v, type = 2, passed = $pcount, price = (SELECT prize FROM ".DB::table('task')." WHERE taskid = $taskid) * $pcount, dateline = ".TIMESTAMP, 'SILENT');
			DB::query("UPDATE ".DB::table('task_count')." SET tomonthmoney = tomonthmoney + (SELECT prize FROM ".DB::table('task')." WHERE taskid = $taskid) * $pcount, extcredits = extcredits + (SELECT prize FROM ".DB::table('task')." WHERE taskid = $taskid) * $pcount, tasked = tasked + $pcount, posts = posts + $pcount WHERE uid = $v");
			$d = array(
				'status' => 1,
				'posts' => $pcount,
				'passed' => $pcount,
				'refused' => 0,
			);
			DB::update('task_user', $d, "uid = $v AND taskid = $taskid" );
		} else {
			$d = array(
				'status' => 1,
				'posts' => $pcount,
				'passed' => 0,
				'refused' => $pcount,
			);
			DB::update('task_user', $d, "uid = $v AND taskid = $taskid" );
		}
	}
	return $return;
}

function viewbind($uid = '') {
	global $_G;
	empty($uid) && $uid = $_G['uid'];
	$sql = "SELECT * FROM ".DB::table('user_sub')." WHERE uid = $uid";
	$q = DB::query($sql);
	while($v = DB::fetch($q)) {
		$return['data'][] = $v;
	}
	return $return;
}

function onebind($uid) {
	$sql = "SELECT windid FROM ".DB::table('user_sub')." WHERE uid = $uid";
	$q = DB::query($sql);
	while($v = DB::fetch($q)) {
		$ids[] = $v['windid'];
	}
	return implode_in($ids);
}

function binduser($windid, $winduser) {
	global $_G;
	DB::insert('user_sub', array('uid'=>$_G['uid'], 'windid' =>$windid, 'windname'=>"$winduser"),false,false,true);
}

function unbinduser($windid) {
	global $_G;
	DB::delete('user_sub', " uid = '{$_G['uid']}' AND windid = '{$windid}'");
	if(DB::affected_rows() == 1) return true;
	else return false;
}

function usercount($uid) {
	$uid = (int) $uid;
	return DB::fetch_first("SELECT * FROM ".DB::table('user_count')." WHERE uid = $uid");
}

function usersub($uid) {
	$uid = (int) $uid;
	$sql = "SELECT * FROM ".DB::table('user_sub')." WHERE uid = $uid";
	$q = DB::query($sql);
	while($r = DB::fetch($q)) {
		$return[] = $r;
	}
	return $return;
}

//总开关
define('API_VERIFYUSER', 1);
define('API_VIEWPOST', 1);
define('API_COUNTPOST', 1);
define('API_SYNLOGIN', 1);
define('API_SYNLOGOUT', 1);

define('API_RETURN_SUCCEED', '1');
define('API_RETURN_FAILED', '-1');
define('API_RETURN_FORBIDDEN', '1');

function init_api() {
	define('API_ROOT', substr(dirname(__FILE__), 0, -20));
	require_once API_ROOT.'./data/sql_config.php';
	
	$_config['db'][9]['dbhost']  		= $dbhost;
	$_config['db'][9]['dbuser']  		= $dbuser;
	$_config['db'][9]['dbpw'] 	 		= $dbpw;
	$_config['db'][9]['dbcharset'] 		= $charset;
	$_config['db'][9]['pconnect'] 		= 0;
	$_config['db'][9]['dbname']  		= $dbname;
	$_config['db'][9]['tablepre'] 		= $PW;
	//在这里对主数据库的需要进行操作的表建立一个映射
	$_config['db']['map'] = array(
								'members' => 9,
								'posts' => 9,
							);
	
	$db = & DB::object();
	$db->set_config($_config['db']);
	$db->connect(9);
	//print_r($db);
}

function do_api($action = 'test', $data) {
	if(in_array($action, array('test', 'verifyuser', 'viewpost', 'countpost', 'synlogin', 'synlogout'))) {
		require_once libfile('class/api');
		init_api();
		$api = new api();
		return $api->$action($data);
	} else {
		return API_RETURN_FAILED;
	}
}

?>
